<template>
  <div class="app-container">
    <!-- 搜索条件 -->
    <el-form :inline="true" class="mb-4">
      <el-form-item label="关键词">
        <el-input
          v-model="queryParams.keyword"
          placeholder="请输入搜索关键词"
          clearable
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="商品ID">
        <el-input
          v-model="queryParams.item_id"
          placeholder="请输入商品ID"
          clearable
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="任务ID">
        <el-input
          v-model="queryParams.task_id"
          placeholder="任务ID"
          clearable
          style="width: 150px"
        />
      </el-form-item>
      <el-form-item label="新商品">
        <el-select
          v-model="queryParams.is_new"
          placeholder="全部"
          clearable
          style="width: 120px"
        >
          <el-option label="全部" value="" />
          <el-option label="是" value="1" />
          <el-option label="否" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="已下单">
        <el-select
          v-model="queryParams.is_ordered"
          placeholder="全部"
          clearable
          style="width: 120px"
        >
          <el-option label="全部" value="" />
          <el-option label="是" value="1" />
          <el-option label="否" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="时间范围">
        <el-date-picker
          v-model="dateRange"
          type="datetimerange"
          range-separator="-"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          style="width: 360px"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 工具栏 -->
    <el-row :gutter="10" class="mb-4">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Refresh" @click="loadRecordList">刷新</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
      </el-col>
    </el-row>

    <!-- 数据列表 -->
    <el-table
      :data="recordList"
      border
      v-loading="loading"
      height="620"
    >
      <el-table-column label="序号" type="index" width="60" align="center" />
      <el-table-column label="关键词" prop="keyword" min-width="120" show-overflow-tooltip />
      <el-table-column label="商品标题" min-width="220">
        <template #default="{ row }">
          <el-tooltip
            v-if="row.item_title"
            effect="dark"
            :content="row.item_title"
            placement="top"
          >
            <span class="title-ellipsis">{{ row.item_title }}</span>
          </el-tooltip>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="商品ID" prop="item_id" min-width="140" show-overflow-tooltip />
      <el-table-column label="价格" width="100" align="center">
        <template #default="{ row }">
          <span v-if="row.item_price">¥{{ row.item_price }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="160" align="center">
        <template #default="{ row }">
          <el-tag :type="row.is_new === '1' ? 'success' : 'info'" size="small">
            {{ row.is_new === '1' ? '新商品' : '旧商品' }}
          </el-tag>
          <el-tag :type="row.is_ordered === '1' ? 'warning' : 'info'" size="small" class="ml-1">
            {{ row.is_ordered === '1' ? '已下单' : '未下单' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="发现时间" width="180" align="center">
        <template #default="{ row }">
          {{ formatDateTime(row.found_time) }}
        </template>
      </el-table-column>
      <el-table-column label="记录时间" width="180" align="center">
        <template #default="{ row }">
          {{ formatDateTime(row.create_time) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="140" fixed="right" align="center">
        <template #default="{ row }">
          <el-button
            link
            type="primary"
            icon="View"
            @click="handleViewDetail(row)"
          >详情</el-button>
          <el-button
            link
            type="primary"
            icon="Link"
            v-if="row.item_url"
            @click="openItemUrl(row.item_url)"
          >链接</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      class="mt-4"
      v-model:current-page="queryParams.pageNum"
      v-model:page-size="queryParams.pageSize"
      :page-sizes="[10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handlePageChange"
      @current-change="handlePageChange"
    />

    <!-- 详情抽屉 -->
    <el-drawer
      v-model="detailDrawerVisible"
      title="商品详情"
      size="40%"
      :destroy-on-close="true"
    >
      <template v-if="currentRecord">
        <el-descriptions :column="1" border size="small">
          <el-descriptions-item label="关键词">{{ currentRecord.keyword || '-' }}</el-descriptions-item>
          <el-descriptions-item label="商品标题">{{ currentRecord.item_title || '-' }}</el-descriptions-item>
          <el-descriptions-item label="商品ID">{{ currentRecord.item_id || '-' }}</el-descriptions-item>
          <el-descriptions-item label="商品链接">
            <el-link
              v-if="currentRecord.item_url"
              :href="currentRecord.item_url"
              target="_blank"
              type="primary"
            >打开链接</el-link>
            <span v-else>-</span>
          </el-descriptions-item>
          <el-descriptions-item label="发现时间">{{ formatDateTime(currentRecord.found_time) }}</el-descriptions-item>
          <el-descriptions-item label="记录时间">{{ formatDateTime(currentRecord.create_time) }}</el-descriptions-item>
          <el-descriptions-item label="原始数据">
            <div class="json-box" v-if="parsedItemData">
              <pre>{{ parsedItemData }}</pre>
            </div>
            <span v-else>-</span>
          </el-descriptions-item>
        </el-descriptions>
      </template>
    </el-drawer>
  </div>
</template>

<script setup>
import { computed, onMounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { getSearchRecordList } from '@/api/agent'

const loading = ref(false)
const total = ref(0)
const recordList = ref([])
const dateRange = ref([])

const queryParams = reactive({
  keyword: '',
  item_id: '',
  task_id: '',
  is_new: '',
  is_ordered: '',
  pageNum: 1,
  pageSize: 20
})

const detailDrawerVisible = ref(false)
const currentRecord = ref(null)

const parsedItemData = computed(() => {
  if (!currentRecord.value || !currentRecord.value.item_data) return null
  try {
    const json = typeof currentRecord.value.item_data === 'string'
      ? JSON.parse(currentRecord.value.item_data)
      : currentRecord.value.item_data
    return JSON.stringify(json, null, 2)
  } catch (error) {
    return currentRecord.value.item_data
  }
})

async function loadRecordList() {
  loading.value = true
  try {
    const params = {
      page_num: queryParams.pageNum,
      page_size: queryParams.pageSize
    }

    if (queryParams.keyword) params.keyword = queryParams.keyword
    if (queryParams.item_id) params.item_id = queryParams.item_id
    if (queryParams.task_id) params.task_id = queryParams.task_id
    if (queryParams.is_new !== '') params.is_new = queryParams.is_new
    if (queryParams.is_ordered !== '') params.is_ordered = queryParams.is_ordered

    if (dateRange.value && dateRange.value.length === 2) {
      params.start_time = toISOString(dateRange.value[0])
      params.end_time = toISOString(dateRange.value[1])
    }

    const { data } = await getSearchRecordList(params)
    recordList.value = data?.rows || []
    total.value = data?.total || 0
  } catch (error) {
    console.error('[SearchRecords] 加载失败', error)
    ElMessage.error(`加载搜索记录失败：${error.message || '未知错误'}`)
    recordList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

function handleQuery() {
  queryParams.pageNum = 1
  loadRecordList()
}

function handleReset() {
  queryParams.keyword = ''
  queryParams.item_id = ''
  queryParams.task_id = ''
  queryParams.is_new = ''
  queryParams.is_ordered = ''
  dateRange.value = []
  queryParams.pageNum = 1
  loadRecordList()
}

function handlePageChange() {
  loadRecordList()
}

function handleExport() {
  ElMessage.info('导出功能开发中，敬请期待~')
}

function handleViewDetail(record) {
  currentRecord.value = record
  detailDrawerVisible.value = true
}

function openItemUrl(url) {
  if (url) {
    window.open(url, '_blank')
  }
}

function formatDateTime(value) {
  if (!value) return '-'
  const date = value instanceof Date ? value : new Date(value)
  if (Number.isNaN(date.getTime())) return '-'
  return date.toLocaleString()
}

function toISOString(value) {
  if (!value) return undefined
  const date = value instanceof Date ? value : new Date(value)
  if (Number.isNaN(date.getTime())) return undefined
  return date.toISOString()
}

onMounted(() => {
  loadRecordList()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.title-ellipsis {
  display: inline-block;
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.json-box {
  background: #1f2933;
  color: #f8fafc;
  padding: 12px;
  border-radius: 4px;
  max-height: 400px;
  overflow: auto;
}

.mb-4 {
  margin-bottom: 16px;
}

.mt-4 {
  margin-top: 16px;
}

.ml-1 {
  margin-left: 4px;
}
</style>

